import { Component, OnInit, Injector, Output, EventEmitter } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ServiceProxy, UserInfoDTO, RoleInfoDTO, SiteDTO } from '@shared/service-proxy/service-proxies';

@Component({
  selector: 'app-edit-user-modal',
  templateUrl: './edit-user-modal.component.html',
  styleUrls: ['./edit-user-modal.component.less']
})
export class EditUserModalComponent extends AppComponentBase implements OnInit {

  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  validateForm: FormGroup;
  isVisible = false;
  isOkLoading = false;
  user: UserInfoDTO = new UserInfoDTO();
  passwordStatus = true;
  title: string;
  roleId: string;
  roles: RoleInfoDTO[] = [];
  sites: SiteDTO[] = [];

  constructor(injector: Injector,
    private fb: FormBuilder,
    private _service: ServiceProxy) {
    super(injector);
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      account: [null, [Validators.required, Validators.maxLength(255)]],
      name: [null, [Validators.required, Validators.email, Validators.maxLength(255)]],
      password: [null, [Validators.required, Validators.maxLength(255)]],
      phone: [null, [Validators.required, Validators.maxLength(255)]],
      roleId: [null, [Validators.required]],
      siteId: [null, [Validators.nullValidator]]
    });
    this.getRoles();
    this.getSites();
  }

  getRoles(): void {
    this._service.getAllRoleInfosUsingGET().subscribe(result => {
      this.roles = result.result.fieldList;
    });
  }

  getSites(): void {
    this._service.getAllSitesUsingGET().subscribe(result => {
      this.sites = result.result.fieldList;
    });
  }

  show(userId?: string) {
    if (userId) {
      this._service.getUserInfoUsingGET(userId).subscribe(result => {
        this.user = result.result;
        this.user.password = undefined;
        this.roleId = this.user.roleInfos[0].id;
        if (!this.user.siteId) {
          this.user.siteId = '';
        }
        this.isVisible = true;
        this.title = this.l("edit");
      });
    } else {
      this.user = new UserInfoDTO();
      this.validateForm.reset();
      this.roleId = '';
      this.user.siteId = '';
      this.isVisible = true;
      this.user.password = '';
      this.title = this.l("create");
    }
  }


  handleOk(): void {
    this.isOkLoading = true;
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    this.user.roleInfoIds = [];
    this.user.roleInfoIds.push(this.roleId);
    if (this.validateForm.valid) {
      if (this.user.id) {
        this._service.updateUserInfoUsingPUT(this.user.id, this.user).subscribe(result => {
          this.isOkLoading = false;
          if (result.success) {
            this.message.success(this.l('save_success'));
            this.close();
            this.modalSave.emit(null);
          } else {
            this.message.info(this.l(result.error.message));
          }

        }, error => {
          this.isOkLoading = false;
          this.message.error(this.l(error.message));
        });
      } else {
        this._service.createUserInfoUsingPOST(this.user).subscribe(result => {
          this.isOkLoading = false;
          if (result.success) {
            this.message.success(this.l('save_success'));
            this.close();
            this.modalSave.emit(null);
          } else {
            this.message.info(this.l(result.error.message));
          }
        }, error => {
          this.isOkLoading = false;
          this.message.error(this.l(error.message));
        });
      }
    } else {
      this.isOkLoading = false;
      this.message.error(this.l('verify_failed_please_check_the_form_item'));
    }
  }

  handleCancel(): void {
    this.close();
  }

  close(): void {
    this.isVisible = false;
  }

}
